package it.low.game.server;

import it.low.game.core.element.ActiveElement;
import it.low.game.core.location.MapPoint;
import it.low.game.server.util.ServerLogManager;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;


public class ServerEngine {
	
	private boolean running = false;
	
	private static Map<String,ActiveElement> activePlayers = new HashMap<String,ActiveElement>();
	private static Map<String,ActiveElement> activeElements = new HashMap<String,ActiveElement>();
	
	public void init(){
		ServerStoring.init();
	}
	
	public void start(){
		running = true;
		this.run();
	}
	
	public static String[][] initMap(){
		String[][] mapDescription = ServerStoring.getMapDecription();
		return mapDescription;
	}
	
	public static ActiveElement initPlayer(String idPlayer){
		ServerLogManager.logMsg("call initPlayer("+idPlayer+")");
		ActiveElement activeElementPlayer = ServerStoring.getElementPlayer(idPlayer);
		if(activeElementPlayer.isInit()){
			ServerLogManager.logMsg("call initPlayer() inizializated");
			activePlayers.put(idPlayer,activeElementPlayer);			
		}else{
			ServerLogManager.logMsg("call initPlayer() not inizializated");
		}
		return activeElementPlayer;
	}
	
	public static ActiveElement initPlayer(String idPlayer, int size, MapPoint mapPosition){
		ServerLogManager.logMsg("call initPlayer("+idPlayer+","+size+","+mapPosition+")");
		ActiveElement activeElementPlayer = ServerStoring.getElementPlayer(idPlayer);
		activeElementPlayer.init(size, mapPosition);
		activePlayers.put(idPlayer,activeElementPlayer);
		return activeElementPlayer;
	}
	
	public static void removePlayer(String idPlayer){
		activePlayers.remove(idPlayer);
	}
	
	public void update(long elapsedTime){
		
	}
	
	public void run(){
		ServerLogManager.logMsg("call run()");
        long startTime = System.currentTimeMillis();
        long currTime = startTime;

        while (Server.running && this.running) {
            long elapsedTime = System.currentTimeMillis() - currTime;
            currTime += elapsedTime;

            // update
            this.update(elapsedTime);
                       
            try {
                Thread.sleep(5);
            }
            catch (InterruptedException ex) { }
        }
	}
	
	public static Set<ActiveElement> getActivePlayers(String idPlayer){
		Set<ActiveElement> playerActivePlayers = new HashSet<ActiveElement>();
		for(ActiveElement activeElement : activePlayers.values()){
			playerActivePlayers.add(activeElement);
		}
		return playerActivePlayers;
	}
	
	public static Set<ActiveElement> getActiveElements(String idPlayer){
		Set<ActiveElement> playerActiveElements = new HashSet<ActiveElement>();
		for(ActiveElement activeElement : activeElements.values()){
			playerActiveElements.add(activeElement);
		}
		return playerActiveElements;
	}
	
}
